package com.hunk.word;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
 * Use FreeMaker Generate Microsoft Word2003-2007
 * 
 * @author HunkDeng
 * @since 2012/11/18
 * @version 001
 * @category utility
 */
public class FmService2 {

	private Configuration configuration = null;

	public FmService2() {

		configuration = new Configuration();

		configuration.setDefaultEncoding("utf-8");

	}

	public void createDoc() {
		// 要填入模本的数据文件
		Map<String,Object> dataMap = new HashMap<String,Object>();		
		getData(dataMap);
		// 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载，
		// 这里我们的模板是放在com.havenliu.document.template包下面
		configuration.setClassForTemplateLoading(
										this.getClass(),
										"/com/hunk/word/template"
										);
		Template t = null;
		try {
			// test.ftl为要装载的模板
			t = configuration.getTemplate("test_2.ftl");
			t.setEncoding("utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 输出文档路径及名称
		File outFile = new File("E:/temp/test2.doc");
		Writer out = null;
		try {
			out = new BufferedWriter(
					new OutputStreamWriter(
							new FileOutputStream(outFile), "utf-8"
							)
					);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			t.process(dataMap, out);
			out.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * 注意dataMap里存放的数据Key值要与模板中的参数相对应
	 * 
	 * 
	 * 
	 * @param dataMap
	 */
	private void getData(Map<String, Object> dataMap) {
		dataMap.put("title", "用户信息");
		dataMap.put("user_name", "张三");
		dataMap.put("user_company", "微软公司");
		
		List<Map<String,String>> rows = new ArrayList<Map<String,String>>();
		for (int i=0;i<3;i++) {
			Map<String,String> row = new HashMap<String, String>();
			row.put("age",String.valueOf(i));
			row.put("width", String.valueOf(i + 10));
			row.put("height", String.valueOf(i + 10));
			rows.add(row);
		}
		dataMap.put("rows", rows);
	}

	@SuppressWarnings("unused")
	private static class Test {
		public static void main(String[] args) {
			FmService2 fm = new FmService2();
			fm.createDoc();
		}
	}
}
